package com.company.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.dao.AdminUserMapper;
import com.company.project.dao.LoginMapper;
import com.company.project.dao.ShopLoginMapper;
import com.company.project.model.Login;
import com.company.project.model.ShopLog;
import com.company.project.model.ShopLogin;
import com.company.project.model.User;
import com.company.project.model.request.EditPassForm;
import com.company.project.model.request.QueryParams;
import com.company.project.model.response.PageList;
import com.company.project.service.AdminUserService;
import com.company.project.core.AbstractService;
import com.company.project.utils.*;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * Created by CodeGenerator on 2020/04/21.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AdminUserServiceImpl extends AbstractService<User> implements AdminUserService {
    @Resource
    private AdminUserMapper adminUserMapper;
    @Autowired
    private ShopLoginMapper shopLoginMapper;
    @Autowired
    private LoginMapper loginMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Result login(User user) {
        User param = new User();
        param.setUsername(user.getUsername());
        User origin = adminUserMapper.selectOne(param);
        if (origin == null) {
            return ResultGenerator.genFailResult("用户名或密码错误");
        }
        String pwd = MD5Util.md5(user.getPassword(), user.getUsername());
        if (!origin.getPassword().equals(pwd)) {
            return ResultGenerator.genFailResult("用户名或密码错误");
        }
        if (user.getRememberMe()) {
            // 设置过期时间为7天
            redisTemplate.opsForValue().set(origin.getUserId(), origin.getUsername(), 7, TimeUnit.DAYS);
        } else {
            // 设置过期时间为30分钟
            redisTemplate.opsForValue().set(origin.getUserId(), origin.getUsername(), 2, TimeUnit.HOURS);
        }
        // 将未登录时购物车的内容添加到用户的购物车
        List<String> notLoginCart = new ArrayList<>();
        if (redisTemplate.hasKey("cart")) {
            notLoginCart = (List<String>) redisTemplate.opsForList().leftPop("cart");
        }
        List<String> cart = new ArrayList<>();
        if (redisTemplate.hasKey(origin.getUserId().toString())) {
            cart = (List<String>) redisTemplate.opsForList().leftPop(origin.getUserId().toString());
        }
        if (notLoginCart != null && notLoginCart.size() > 0) {
            cart.addAll(notLoginCart);
        }
        redisTemplate.opsForList().leftPush(origin.getUserId().toString(), cart);

        return ResultGenerator.genSuccessResult(origin.getUserId());
    }

    @Override
    public Result register(User user) {
        String code = (String) redisTemplate.opsForValue().get(user.getUsername());
        if (!user.getCode().equals(code)) {
            return ResultGenerator.genFailResult("邮箱验证码错误");
        }
        user.setStatus("1");
        user.setRole("用户");
        user.setCreatTime(new Date());
        // 密码加密
        user.setPassword(MD5Util.md5(user.getPassword(), user.getUsername()));
        adminUserMapper.insert(user);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result sendCode(String email) {
        String code = StringRandom.getStringRandom(6);
        // 设置验证码有效期为10分钟
        redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
        // 创建发送邮件线程并启动
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                ThreadPool.corePoolSize,
                ThreadPool.maximumPoolSizeSize,
                ThreadPool.keepAliveTime,
                TimeUnit.SECONDS,
                ThreadPool.workQueue,
                new ThreadFactoryBuilder().setNameFormat("XX-task-%d").build());
        threadPoolExecutor.execute(new MailUtil(email, code));

        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result logout(Integer id) {
        if (redisTemplate.hasKey(id)) {
            redisTemplate.delete(id);
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult("用户不存在或者已经过期");
    }

    @Override
    public Result updatePwd(EditPassForm editPassForm) {
        User query = new User();
        query.setUserId(editPassForm.getUserId());
        User user = adminUserMapper.selectOne(query);
        String inputOldPwd = MD5Util.md5(editPassForm.getEditPass().getOldPwd(), editPassForm.getUsername());
        if (!user.getPassword().equals(inputOldPwd)) {
            return ResultGenerator.genFailResult("原密码输入有误，请重新输入");
        }
        String newPwd = MD5Util.md5(editPassForm.getEditPass().getNewPwd(), editPassForm.getUsername());
        user.setPassword(newPwd);
        adminUserMapper.updateByPrimaryKey(user);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result updateInfo(User user) {
        User old = adminUserMapper.selectByPrimaryKey(user.getId());

        String projectPath = System.getProperty("user.dir");
        if (StringUtils.isNotBlank(user.getImg())) {
            String filePath = projectPath + "\\src\\main\\resources\\static\\" + user.getImg();
            String headImg = ImageBinary.getImageBinary(filePath);
            old.setHeadImg(headImg);
        }

        old.setName(user.getName());
        old.setAddress(user.getAddress());
        old.setTelephone(user.getTelephone());
        adminUserMapper.updateByPrimaryKey(old);

        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result getUserList(QueryParams queryParams) {
        int page = queryParams.getPage();
        int size = queryParams.getSize();
        queryParams.setStart((page - 1) * size);
        List<User> list = adminUserMapper.getUserList(queryParams);
        Integer total = adminUserMapper.getUserListTotal(queryParams);
        PageList<User> pageList = new PageList<>();
        pageList.setList(list);
        pageList.setTotal(total);
        return ResultGenerator.genSuccessResult(pageList);
    }

    @Override
    public Result delete(Integer id) {
        User user = new User();
        user.setUserId(id);
        User entity = adminUserMapper.selectOne(user);
        entity.setStatus("2");
        adminUserMapper.updateByPrimaryKey(entity);
        return ResultGenerator.genSuccessResult();
    }
}
